<?php

class GenerateData_API_Endpoint {

    public function __construct() {
        add_filter('query_vars', array($this, 'add_query_vars'), 0);
        add_action('parse_request', array($this, 'sniff_requests'), 0);
        add_action('init', array($this, 'add_endpoint'), 0);
    }

    /** Add public query vars
     * 	@param array $vars List of current public query vars
     * 	@return array $vars 
     */
    public function add_query_vars($vars) {
        $vars[] = '__api';
        $vars[] = 'user';
        $vars[] = 'action';
        return $vars;
    }

    /** Add API Endpoint
     * 	This is where the magic happens - brush up on your regex skillz
     * 	@return void
     */
    public function add_endpoint() {
        add_rewrite_rule('^api/generate-data/([0-9]+)?/?', 'index.php?__api=1&action=fe_gendata&user=$matches[1]', 'top');
    }

    /** 	Sniff Requests
     * 	This is where we hijack all API requests
     * 	If $_GET['__api'] is set, we kill WP and serve up pug bomb awesomeness
     * 	@return die if API request
     */
    public function sniff_requests() {
        global $wp;
        if (isset($wp->query_vars['action']) && $wp->query_vars['action'] == "fe_gendata") {
            $this->handle_request();
            exit;
        }
    }

    /** Handle Requests
     * 	This is where we send off for an intense pug bomb package
     * 	@return void 
     */
    protected function handle_request() {
        
        global $wp, $wpdb;
        
        $func = $wp->query_vars['func'];
        
        $current_user = wp_get_current_user();
        $current_user_id = $current_user->ID;
        
        $current_year = date('Y');
        $current_month = date('n');
        
        if ($_GET['func'] == 'genBaseLine') {

            $wpdb->query("delete from bpa_registry_baseline");
            
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    $base = rand(0, 10) / 10;
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_baseline (type_id, year, month, base) 
                        values (%d, %d, %d, %f)", 1, $y, $m, $base));
                    $base = rand(0, 10) / 10;
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_baseline (type_id, year, month, base) 
                        values (%d, %d, %d, %f)", 2, $y, $m, $base));
                }
            }
            
            $this->send_response('OK', "BaseLine data generated");
            
        }else if ($_GET['func'] == 'genUserData') {
            
            if(!isset($_GET['user'])){
                $this->send_response('Error', "Parameter user not found");
                exit;
            }
            
            $user_id = $_GET['user'];
            $wpdb->query($wpdb->prepare("delete from bpa_registry_consumption where user_id = %d", $user_id));
            $wpdb->query($wpdb->prepare("delete from bpa_registry_product where user_id = %d", $user_id));
            $wpdb->query($wpdb->prepare("delete from bpa_registry_sector where user_id = %d", $user_id));
            $wpdb->query($wpdb->prepare("delete from bpa_registry_workers where user_id = %d", $user_id));
            
            $sector = 2;
            $subsector = 39;
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_sector (user_id, sector_id, subsector_id, year, month) 
                        values (%d, %d, %d, %d, %d)", $user_id, $sector, $subsector, $y, $m));
                }
            }
            
            $product = 4;
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_product (user_id, product_id, year, month) 
                        values (%d, %d, %d, %d)", $user_id, $product, $y, $m));
                }
            }
            
            $workers = rand(10, 30);
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    $wpdb->query($wpdb->prepare("insert into bpa_registry_workers (user_id, year, month, number) 
                        values (%d, %d, %d, %d)", $user_id, $y, $m, $workers));
                }
            }
            
            $types = $wpdb->get_results("select t.id as type_id, st.id as subtype_id from bpa_consumption_type t left join bpa_consumption_subtype st on t.id = st.type_id");
            
            for($y = 2010; $y <= $current_year; $y++){
                $end_month = $y < $current_year ? 12 : $current_month;
                for($m = 1; $m <= $end_month; $m++){
                    foreach($types as $type){
                        $type_id = $type->type_id;
                        $subtype_id = $type->subtype_id == null ? 0 : $type->subtype_id;
                        $quantity = rand(100, 800);
                        $price = rand(100, 5000);
                        $wpdb->query($wpdb->prepare(
                        "insert into bpa_registry_consumption (user_id, type_id, subtype_id, year, month, quantity, price) 
                        values (%d, %d, %d, %d, %d, %d, %f)", $user_id, $type_id, $subtype_id, $y, $m, $quantity, $price));
                    }
                }
            }
            
            $this->send_response('OK', "User data generated");
            
        }
        
    }

    /** Response Handler
     * 	This sends a JSON response to the browser
     */
    protected function send_response($msg, $user = '') {
        $response['message'] = $msg;
        if ($user)
            $response['data'] = $user;
        header('content-type: application/json; charset=utf-8');
        echo json_encode($response) . "\n";
        exit;
    }

}

new GenerateData_API_Endpoint();